/*
 *  Copyright 2015-2016, RenGu Technology (BeiJing) Co., Ltd.
 *  All right reserved.
 *
 *  THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE OF RENGU TECHNOLOGY (BeiJing) CO., LTD.
 *
 *  THE CONTENTS OF THIS FILE MAY NOT BE DISCLOSED TO THIR PARTIES,
 *  COPIED OR DUPLICATED IN ANY FORM, IN WHOLE OR IN PART,
 *  WITHOUT THE PRIOR WRITTEN PERMISSION OF RENGU TECHNOLOGY (BeiJing) CO., LTD.
 *
 *  VirtAcctTransDetailQueryService
 *
 *  Edit History:
 *      lizhangtao Created on 2020年05月14日
 *
 */
package cc.rengu.igas.acct.core.service.trans;

import cc.rengu.igas.acct.common.dao.AcctDetailMapper;
import cc.rengu.igas.acct.common.dao.impl.AcctDetailMapperImpl;
import cc.rengu.igas.acct.common.entity.AcctDetail;
import cc.rengu.igas.acct.common.enums.AcctRespCodeEnum;
import cc.rengu.igas.acct.facade.bean.AcctDetailInfo;
import cc.rengu.igas.acct.facade.request.VirtAcctTransDetailQueryRequest;
import cc.rengu.igas.acct.facade.response.VirtAcctTransDetailQueryResponse;
import cc.rengu.oltp.service.base.RadpService;
import cc.rengu.oltp.service.common.constant.TreeNodeConstant;
import cc.rengu.oltp.service.common.enums.ChannelEnum;
import cc.rengu.oltp.service.common.enums.OltpRpcdEnum;
import cc.rengu.oltp.service.common.enums.TransStatusEnum;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.utility.bean.PageResult;
import cc.rengu.oltp.utility.util.BeanUtil;
import cc.rengu.oltp.utility.util.ConvertUtil;
import cc.rengu.oltp.utility.util.XmlTreeUtil;
import cc.rengu.utility.base.StringUtil;
import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 日期时间段内交易明细查询
 * 日期为外部上送的交易日期
 * TODO 是否能查询当天数据？
 *
 * @author lizhangtao
 * @version 1.0
 * @date 2020/5/10
 */
public class VirtAcctTransDetailQueryService extends RadpService {
    @Override
    protected int bizInit(String s) {
        return 0;
    }

    @Override
    protected int bizProcess(String s, int i) {
        //上送字段检查
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        try {
            VirtAcctTransDetailQueryRequest virtAcctTransDetailQueryRequest = new VirtAcctTransDetailQueryRequest();
            ConvertUtil.convertOutput(virtAcctTransDetailQueryRequest);
            rglog.info("virtAcctTransDetailQueryRequest = <{}>", JSONObject.toJSONString(virtAcctTransDetailQueryRequest));
            VirtAcctTransDetailQueryResponse virtAcctTransDetailQueryResponse = new VirtAcctTransDetailQueryResponse();
            virtAcctTransDetailQueryResponse.setHeader(virtAcctTransDetailQueryRequest.getHeader());
            BizResponse<VirtAcctTransDetailQueryResponse> bizResponse = new BizResponse<>();
            bizResponse.setResult(virtAcctTransDetailQueryResponse);
            String instId = virtAcctTransDetailQueryRequest.getHeader().getInstId();
            String acctNo = virtAcctTransDetailQueryRequest.getAcctNo();
            String acctType = virtAcctTransDetailQueryRequest.getAcctType();
            String customerId = virtAcctTransDetailQueryRequest.getCustomerId();
            String userId = virtAcctTransDetailQueryRequest.getUserId();
            String userType = virtAcctTransDetailQueryRequest.getUserType();
            String startDate = virtAcctTransDetailQueryRequest.getStartDate();
            String endDate = virtAcctTransDetailQueryRequest.getEndDate();
            String pageNo = virtAcctTransDetailQueryRequest.getPageNo();
            String numPerPage = virtAcctTransDetailQueryRequest.getNumPerPage();
            int pageNoInt = 0;
            int numPerPageInt = 20;
            if (StringUtil.isNullorEmpty(acctNo) &&
                    StringUtil.isNullorEmpty(customerId) &&
                    (StringUtil.isNullorEmpty(userType) || StringUtil.isNullorEmpty(userId))) {
                rglog.error("账户号、客户id，外部用户类型&外部用户id必须三选一");
                throw new BizException(AcctRespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(),
                        AcctRespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
            }
            //必填项
            if (StringUtil.isNullorEmpty(acctType) || StringUtil.isNullorEmpty(startDate) || StringUtil.isNullorEmpty(endDate)) {
                rglog.error("账户类型、交易开始日期，交易截止日期必输");
                throw new BizException(AcctRespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(),
                        AcctRespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
            }
            //页数默认为0，每页记录数默认为20
            if (!StringUtil.isNullorEmpty(pageNo)) {
                pageNoInt = Integer.parseInt(pageNo);
            }
            if (!StringUtil.isNullorEmpty(numPerPage)) {
                numPerPageInt = Integer.parseInt(numPerPage);
            }
            //查询时间段内交易明细，起止日期使用交易日期而非账务日期
            AcctDetailMapper acctDetailMapper = new AcctDetailMapperImpl();
            PageResult pageResult;
            //账号不为空使用账号查询
            if (!StringUtil.isNullorEmpty(acctNo)) {
                rglog.info("使用账号查询<{}>", acctNo);
                pageResult = acctDetailMapper.fetchPageListByAcctNoAndStartEndDate(instId,
                        acctNo, startDate, endDate, numPerPageInt, pageNoInt);
            }
            //使用客户号查询
            else if (!StringUtil.isNullorEmpty(customerId)) {
                rglog.info("使用客户号查询<{}>", customerId);
                pageResult = acctDetailMapper.fetchPageListByCustomerIdAndStartEndDate(instId,
                        customerId, startDate, endDate, numPerPageInt, pageNoInt);
            }
            //使用外部用户查询
            else if (!StringUtil.isNullorEmpty(userType) && !StringUtil.isNullorEmpty(userId)) {
                rglog.info("使用外部用户查询<{}><{}>", userType, userId);
                pageResult = acctDetailMapper.fetchPageListByUserAndStartEndDate(instId,
                        userType, userId, startDate, endDate, numPerPageInt, pageNoInt);
            } else {
                throw new BizException(AcctRespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(),
                        AcctRespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
            }

            if (null == pageResult || null == pageResult.getPageInfo() || 0 == pageResult.getPageInfo().getTotalRows() ||
                    null == pageResult.getResult() || 0 == pageResult.getResult().size()) {
                rglog.error("未查询到数据");
                throw new BizException(AcctRespCodeEnum.NO_TRANS_RECORD.getRespCode(), AcctRespCodeEnum.NO_TRANS_RECORD.getRespDesc());
            }
            List<Object> acctDetailList = pageResult.getResult();
            List<AcctDetailInfo> acctDetailInfoList = new ArrayList<>();
            for (Object objTemp : acctDetailList) {
                AcctDetail acctDetail = (AcctDetail) objTemp;
                //校验账户、客户号、外部用户
                if (!StringUtil.isNullorEmpty(acctNo) && !acctNo.equals(acctDetail.getAcctNo())) {
                    rglog.error("上送账号<{}>与记录不符<{}>", acctNo, acctDetail.getAcctNo());
                    throw new BizException(AcctRespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(),
                            AcctRespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
                }
                if (!StringUtil.isNullorEmpty(customerId) && !customerId.equals(acctDetail.getCustomerId())) {
                    rglog.error("上送客户号<{}>与记录不符<{}>", customerId, acctDetail.getCustomerId());
                    throw new BizException(AcctRespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(),
                            AcctRespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
                }
                if ((!StringUtil.isNullorEmpty(userType) && !StringUtil.isNullorEmpty(userId))) {
                    if (!userType.equals(acctDetail.getUserType()) || !userId.equals(acctDetail.getUserId())) {
                        rglog.error("上送用户<{}><{}>与记录不符<{}><{}>", userType, userId, acctDetail.getUserType(), acctDetail.getUserId());
                        throw new BizException(AcctRespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(),
                                AcctRespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
                    }
                }
                AcctDetailInfo acctDetailInfo = new AcctDetailInfo();
                acctDetailInfoList.add(acctDetailInfo);
                BeanUtil.beanCopy(acctDetail, acctDetailInfo);
                acctDetailInfo.setTransSeqNum(acctDetail.getFrontSeqNum());
            }
            virtAcctTransDetailQueryResponse.setAcctDetailInfoList(acctDetailInfoList);
            virtAcctTransDetailQueryResponse.setNumPerPage(numPerPage);
            virtAcctTransDetailQueryResponse.setPageNo(pageNo);
            virtAcctTransDetailQueryResponse.setTotalNum(String.valueOf(pageResult.getPageInfo().getTotalRows()));
            virtAcctTransDetailQueryResponse.setRespCode(OltpRpcdEnum.TRANS_SUCCESS.getRespCode());
            virtAcctTransDetailQueryResponse.setRespDesc(OltpRpcdEnum.TRANS_SUCCESS.getRespDesc());
            bizResponse.setRspSysId(ChannelEnum.ACCT.getChannelType());
            bizResponse.setRespCode(OltpRpcdEnum.TRANS_SUCCESS.getRespCode());
            bizResponse.setRespDesc(OltpRpcdEnum.TRANS_SUCCESS.getRespDesc());
            bizResponse.setTransStatus(TransStatusEnum.TRANS_SUCC);

            ConvertUtil.convertInput(bizResponse.getResult());
        } catch (BizException e) {
            try {
                xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.RESP_CODE, e.getCode());
                xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.RESP_DESC, e.getMessage());
            } catch (Exception e1) {
                rglog.error(StringUtil.ExceptionToString(e1));
            }
        } catch (Exception e) {
            rglog.error(StringUtil.ExceptionToString(e));
            try {
                xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.RESP_CODE,
                        OltpRpcdEnum.BIZ_PROCESS_TIMEOUT.getRespCode());
                xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.RESP_DESC,
                        OltpRpcdEnum.BIZ_PROCESS_TIMEOUT.getRespDesc());
            } catch (Exception e1) {
                rglog.error(StringUtil.ExceptionToString(e));
            }
        }
        return 0;
    }

    @Override
    protected int bizTerminate(String s) {
        return 0;
    }
}
